var userAgent = navigator.userAgent.toLowerCase();
var currentTime = Math.round(new Date().getTime()/1000).toString();

$(document).ready(function(){
    shortDetial();
});

function getShortId() {
    var currentPath = window.location.pathname;
    pathParamas = currentPath.split("/");
    return pathParamas[pathParamas.length-1];
}

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function getSystem() {
    if (userAgent.search("windows nt") != -1) {
        pvendor = 4;
    } else if (userAgent.search("iphone") != -1) {
        pvendor = 2;
    } else if (userAgent.search("ipad") != -1) {
        pvendor = 3;
    } else if (userAgent.search("android") != -1) {
        pvendor = 1;
    } else if (userAgent.search("macintosh") != -1) {
        pvendor = 5;
    } else {
        pvendor = 0;
    }
    return pvendor;
}

function getBrowserCode() {
    // 判断访问是什么设备
    if (userAgent.search('jssdk') != -1 || userAgent.search('aweme') != -1 || userAgent.search('bytelocale') != -1 || userAgent.search('bytedancewebview') != -1) {
        // 头条系
        if (userAgent.search('douyin_lite') != -1 || userAgent.search('aweme_lite') != -1) {
            // 抖音极速版
            browser = 27;
        } else if (userAgent.search('aweme_hotsoon') != -1 || userAgent.search('live_stream') != -1) {
            // 抖音火山版
            browser = 28;
        } else if (userAgent.search('newsarticle') != -1) {
            if (userAgent.search('newslite') != -1) {
                // 今日头条极速版
                browser = 30;
            } else {
                // 今日头条
                browser = 29;
            }
        } else if (userAgent.search('videoarticle') != -1) {
            // 西瓜视频
            browser = 31;
        } else {
            // 抖音
            browser = 26;
        }
    } else if (userAgent.search('baiduboxapp') != -1) {
        if (userAgent.search('matrixstyle')  != -1) {
            // 百度极速版
            browser = 33;
        } else {
            // 百度
            browser = 9;
        }
    } else if (userAgent.search('micromessenger') != -1) {
        // 微信浏览器
        browser = "1";
    } else if(userAgent.search('qqbrowser') != -1){
        // 电脑QQ浏览器
        browser = "2";
    } else if(userAgent.search('vivobrowser') != -1){
        // Vivo浏览器
        browser = "3";
    } else if(userAgent.search('heytapbrowser') != -1){
        // Oppo浏览器
        browser = "4";
    } else if(userAgent.search('huaweibrowser') != -1){
        // 华为浏览器
        browser = "5";
    } else if(userAgent.search('miuibrowser') != -1){
        // 小米浏览器
        browser = "6";
    } else if(userAgent.search('mqqbrowser') != -1){
        // QQ浏览器
        browser = "7";
    } else if(userAgent.search('alipayclient') != -1){
        // 支付宝浏览器
        browser = "8";
    } else if(userAgent.search('baiduboxapp') != -1){
        // 百度APP
        browser = "9";
    } else if(userAgent.search('weibo') != -1){
        // 微博浏览器
        browser = "10";
    } else if(userAgent.search('iqiyi') != -1){
        // 爱奇艺浏览器
        browser = "11";
    } else if(userAgent.search('miuibrowser') != -1 || userAgent.search('xiaomi') != -1){
        // 小米浏览器
        browser = "12";
    } else if(userAgent.search('kdtunion_iting') != -1){
        // 喜马拉雅
        browser = "13";
    } else if(userAgent.search('dingtalk') != -1){
        // 钉钉
        browser = "14";
    } else if(userAgent.search('ucbrowser') != -1){
        // UC浏览器
        browser = "15";
    } else if(userAgent.search('samsungbrowser') != -1){
        // 三星浏览器
        browser = "16";
    } else if(userAgent.search('nokiabrowser') != -1){
        // 诺基亚浏览器
        browser = "17";
    } else if(userAgent.search('opera') != -1){
        // 欧朋
        browser = "18";
    } else if(userAgent.search('firefox') != -1){
        // 火狐
        browser = "19";
    } else if(userAgent.search('zhihu') != -1 || userAgent.search('hihu') != -1){
        // 知乎
        browser = "20";
    } else if(userAgent.search('larkLocale') != -1){
        browser = "21";
    } else if(userAgent.search('iphone') != -1){
        browser = "22";
    } else if(userAgent.search('ipad') != -1){
        browser = "23";
    } else if(userAgent.search('macintosh') != -1){
        browser = "24";
    } else {
        browser = "25";
    }
    return browser;
}

function getDevice() {
    var isIphone = userAgent.match(/iphone/i) == "iphone";
    var isHuawei = userAgent.match(/huawei/i) == "huawei";
    var isHonor = userAgent.match(/honor/i) == "honor";
    var isOppo = userAgent.match(/oppo/i) == "oppo";
    var isRealme = userAgent.match(/rmx/i) == "rmx";
    var isOppoR15 = userAgent.match(/pacm00/i) == "pacm00";
    var isVivo = userAgent.match(/vivo/i) == "vivo";
    var isXiaomi = userAgent.match(/mi\s/i) == "mi ";
    var isXiaomi2s = userAgent.match(/mix\s/i) == "mix ";
    var isRedmi = userAgent.match(/redmi/i) == "redmi";
    var isSamsung = userAgent.match(/sm-/i) == "sm-";
    if (isIphone) {
        return 6;
    } else if (isHuawei || isHonor) {
        return 1;
    } else if (isOppo || isOppoR15 || isRealme) {
        return 4;
    } else if (isVivo) {
        return 2;
    } else if (isXiaomi || isRedmi || isXiaomi2s) {
        return 3;
    } else if (isSamsung) {
        return 5;
    } else {
        return 0;
    }
}

function getRecordId(short_id) {
    var storageRecordId = localStorage.getItem("record_id_"+short_id) || "";
    if (storageRecordId == "") {
        var tableId = (new Date().getMonth()+1) % 4;
        var vertify = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var sd = '';
        for (var i = 0; i < 6; i++) {
            var random = Math.floor(Math.random() * (vertify.length));
            sd += vertify[random];
        }
        record_id = tableId+$.md5(short_id+currentTime+sd);
        localStorage.setItem("record_id_"+short_id,record_id);
    } else {
        record_id = storageRecordId;
    }
    return record_id;
}

function shortDetial() {
    var short_id = getShortId();
    var system = getSystem();
    var browser = getBrowserCode();
    var device = getDevice();
    var code = getQueryString("code");
    var record_id = getRecordId(short_id);
    var sign = $.md5(short_id+"sk"+currentTime);
    var short_url = localStorage.getItem("short_"+short_id) || "";
    if (short_url != "") {
        window.location.href = short_url;
        return;
    }

    $.ajax({
        url: 'https://api.kuaitiaourl.cn/api/version/1.0/short/record_static',
        data: {"short_id":short_id,"system":system,"browser":browser,"device":device,"code":code,"record_id":record_id,"sign":sign,"key":currentTime},
        success: (result) => {
            if (result.status == "success") {
                var short = result.data.short;
                if (short.deadline <= currentTime) {
                    errorNotice("会员过期提醒","请续费后继续使用短链接!");
                    return;
                }
                if (short.end_time >= 100 && short.end_time <= currentTime) {
                    errorNotice("链接已失效","当前链接已失效,请访问别的链接!");
                    return;
                }
                if (short.status == 3) {
                    errorNotice("链接已删除","当前链接已删除,请访问别的链接!");
                    return;
                } else if (short.status == 2) {
                    errorNotice("链接已暂停","当前链接已暂停访问,请访问别的链接!");
                    return;
                }
                // var domain = window.location.host;
                // if (short.domain != domain) {
                //     errorNotice("链接不存在","当前链接不能存在,请检查链接是否正确!");
                //     return;
                // }
                var urlCheck = isValidURL(short.link);
                if (urlCheck) {
                    window.location.href = short.link;
                } else {
                    errorNotice("跳转网址错误","长链接请配置带http的长连接!");
                    return;
                }
                localStorage.setItem("short_"+short_id,short.link);
            } else {
                errorNotice("访问链接失败",result.msg);
            }
        },
        error: (errormsg) => {
            errorNotice("网络异常","请检查网络是否正常!");
        }
    });
}

function isValidURL(url) {
    var pattern = /^(http|https):\/\/[^ "]+$/;
    return pattern.test(url);
}

function errorNotice(title,describe) {
    $("body").html('<div class="error-notice"><img src="https://dwzy.oss-cn-beijing.aliyuncs.com/img/error.png"><h3>'+title+'</h3><h5>'+describe+'</h5></div>');
}
